//
//  ZXY_TimerHelper.m
//  CoreDataDemo
//
//  Created by 宇周 on 15/12/9.
//  Copyright © 2015年 宇周. All rights reserved.
//

#import "ZXY_TimerHelper.h"
@interface ZXY_TimerHelper()
{
    int maxCount_s;
    uint64_t leeway_s;
    uint64_t interval_s;
    void (^ timerAction)();
}
@property(nonatomic , copy)void(^ timerToZero)();
@property(nonatomic , copy)void(^ timerChanged)(int);

@end
@implementation ZXY_TimerHelper
- (id)init
{
    if(self = [super init])
    {
        maxCount_s = 10;
        leeway_s = 0;
        interval_s = 1;
    }
    return self ;
}

dispatch_source_t mainTimer;
int currentTime ;

dispatch_source_t CreateTimer(uint64_t interval , uint64_t leeway , dispatch_queue_t queue , dispatch_block_t block)
{
    dispatch_source_t timerCurrent = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    if(timerCurrent)
    {
        dispatch_source_set_timer(timerCurrent, dispatch_walltime(NULL, 0), 1ull * NSEC_PER_SEC, leeway );
        dispatch_source_set_event_handler(timerCurrent, block);
        dispatch_resume(timerCurrent);
    }
    return timerCurrent;
}

- (void)setTimerInfoInVal:(uint64_t)interval
              andMaxTimer:(int)maxCount
                   leeWay:(uint64_t)leeway
   withChangeToZeroAction:(void (^)())changeToZero
     andTimerCountChanged:(void (^)(int))currentCount
{
    self->maxCount_s = maxCount;
    self->leeway_s   = leeway;
    self->interval_s = interval;
    self.timerChanged = currentCount;
    self.timerToZero  = changeToZero;
    currentTime = self->maxCount_s;
    [self startBegain];
}

- (void)startBegain
{
    __weak ZXY_TimerHelper *weakSelf = self;
    timerAction = ^(){
        [weakSelf startTimerChange];
    };
    if(mainTimer == nil)
    {
        mainTimer = CreateTimer(interval_s, leeway_s, dispatch_get_main_queue(), timerAction);
    }
    else
    {
        dispatch_resume(mainTimer);
    }
}

- (void)startTimerChange
{
    currentTime--;
    if(currentTime <= 0)
    {
        if(self.timerToZero)
        {
            self.timerToZero();
        }
    }
    else
    {
        if(self.timerChanged)
        {
            self.timerChanged(currentTime);
        }
    }
}

- (void)restart:(BOOL)isRefresh
{
    if(isRefresh)
    {
        currentTime = self -> maxCount_s;
        dispatch_resume(mainTimer);
    }
    else
    {
        dispatch_resume(mainTimer);
    }
}


- (void)stopTimer
{
    dispatch_suspend(mainTimer);
}
@end
